<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MUser;
use App\Utils\ComUtil;

/**
 * 文件安全管理控制器
 */
class FileController extends Controller
{
    /**
     * 数据导出页面
     */
    public function exportPage()
    {
        $publicDir = public_path('exports');
        $files = ComUtil::dirFileByTime($publicDir, ".xls");
        $this->data['files'] = $files;
        return view('admin.exports')->with($this->data);
    }

    /**
     * Excel文件导出功能
     */
    public function exportUsers()
    {
        if (MUser::exportToFile()) {
            $this->data = $this->makeJsCode(0, "数据导出成功！");
        } else {
            $this->data = $this->makeJsCode(1, "数据导出失败！");
        }
        return back()->with($this->data);
    }

    /**
     * 数据库备份文件列表页面
     */
    public function sqlsPage()
    {
        $public_dir = public_path('sqls');
        $files = ComUtil::dirFileByTime($public_dir, ".sql");
        $this->data['files'] = $files;
        return view('admin.sqls')->with($this->data);
    }

    /**
     * 执行数据库手动备份
     */
    public function sqlBakAct()
    {
        $u = env("DB_USERNAME");
        $p = env("DB_PASSWORD");
        $db = env("DB_DATABASE");

        $filename = public_path('sqls\\') . date('Y-m-d_H_i') . ".sql";
        $cmd = "mysqldump --opt -Q -u$u -p$p --default-character-set=utf8 $db > $filename";
        exec($cmd);
        Mlog::log("执行数据库手动备份",6);
        $this->data = $this->makeJsCode(0, "请耐心等待，1-10分钟以内将会备份成功！");
        return back()->with($this->data);
    }


    /**
     * 从服务器上下载一个备份/导出
     */
    public function downFile($key)
    {
        $path = public_path(base64_decode($key));
        return response()->download($path);
    }

    /**
     * 从服务器上删除一个备份/导出
     */
    public function delFile($key)
    {
        $path = public_path(base64_decode($key));
        if (unlink($path)) {
            $this->data = $this->makeJsCode(0, "删除成功！");
        } else {
            $this->data = $this->makeJsCode(1, "删除失败！");
        }
        return back()->with($this->data);
    }
}
